import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/config/app_routes.dart';
import '../../config/app_theme.dart';
import '../../entity/game.dart';
import '../../provider/user_provider.dart';
import '../../provider/wishlist_provider.dart';
import '../widgets/user_avatar.dart';

class WishlistPage extends StatefulWidget {
  final VoidCallback onBack;

  const WishlistPage({super.key, required this.onBack});

  @override
  State<WishlistPage> createState() => _WishlistPageState();
}

class _WishlistPageState extends State<WishlistPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final user = context.read<UserProvider>().currentUser;
      if (user != null) {
        context.read<WishlistProvider>().fetchWishlist(user.id);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final user = context.watch<UserProvider>().currentUser;
    final provider = context.watch<WishlistProvider>();

    if (user == null) {
      return const Center(child: CircularProgressIndicator());
    }

    final games = provider.wishlistGames;
    final isLoading = provider.isLoading;
    final error = provider.errorMessage;

    return Column(
      children: [
        // 顶部区域
        Padding(
          padding: const EdgeInsets.all(hPaddingSize),
          child: Row(
            children: [
              GestureDetector(
                onTap: widget.onBack,
                child: const Icon(Icons.arrow_back_ios, color: Colors.white),
              ),
              const SizedBox(width: 12),
              UserAvatar(user: user, radius: 0),
              const SizedBox(width: 12),
              Text('${user.name}的愿望单',
                  style: const TextStyle(fontSize: 18, fontWeight: titleFontWeight, color: textColor)),
            ],
          ),
        ),

        // 内容区域
        Expanded(
          child: isLoading
              ? const Center(child: CircularProgressIndicator())
              : error != null
              ? Center(child: Text(error, style: const TextStyle(color: Colors.white70)))
              : games.isEmpty
              ? const Center(
            child: Text('您的愿望单为空', style: TextStyle(color: Colors.white70)),
          )
              : ListView.builder(
            itemCount: games.length,
            itemBuilder: (context, index) {
              final game = games[index];
              return _buildGameItem(game, user.id);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildGameItem(Game game, String userId) {
    final wishlistProvider = context.read<WishlistProvider>();

    final price = game.products.isNotEmpty
        ? '¥${game.products.first.price.toStringAsFixed(2)}'
        : '暂无定价';

    return Card(
      color: Colors.grey[900],
      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
      child: ListTile(
        contentPadding: const EdgeInsets.all(12),
        title: Text(
          game.name,
          style: const TextStyle(fontSize: titleFontSize, fontWeight: titleFontWeight, color: textColor),
        ),
        subtitle: Text(
          game.developer,
          style: const TextStyle(color: Colors.white70),
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(price, style: const TextStyle(color: priceTagTextColor)),
            const SizedBox(width: 8),
            IconButton(
              icon: const Icon(Icons.delete_outline, color: dimTextColor),
              tooltip: '移除',
              onPressed: () async {
                await wishlistProvider.removeGameFromWishlist(userId, game.id);
              },
            ),
          ],
        ),
        onTap: () {
          Navigator.of(context).pushNamed(
            gameDetail_page,
            arguments: game,
          );
        },
      ),
    );
  }
}
